var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var jwt = require('jsonwebtoken')
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var yzkRouter = require('./routes/yzk');
// 王佑新
var xinRouter = require('./routes/xin');
// 牛晓
var Niux = require('./routes/Niux');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(cors());
// 认证中间件
const authMiddleware = (req, res, next) => {

  const whiteList = [
    '/users/faceLogin',
    '/users/loginimg',
    '/users/img',
    '/users/register',
    '/users/login',
    '/users/facelogin',
    '/users/phone',
    '/users/get_sms'
    
  ];
  
  //如果请求的路由在白名单中，直接跳过验证
  if (whiteList.includes(req.path)) {
    console.log('白名单');
    return next();
  }

  const authorizationHeader = req.headers.authorization;
  
  if (!authorizationHeader) {
    
    return res.status(401).json({ message: 'Authorization header missing' });
  }

  const token = authorizationHeader.replace('Bearer ', '');

  jwt.verify(token, 'face', (err, decode) => {
    if (err) {
      // 令牌过期或其他验证错误
      if (err.name === 'TokenExpiredError') {
        // 生成新的令牌
        const newToken = jwt.sign({ users: 'niu' }, "face", { expiresIn: '3s' });
        // 设置新的令牌到响应头
        res.setHeader('Authorization', `Bearer ${newToken}`);
        // 继续处理请求
        return next();
      } else {
        // 其他验证错误
        return res.status(401).json({ message: 'Invalid token' });
      }
    }

    // 如果验证成功，继续处理请求
    req.user = decode; // 将解码后的用户信息附加到请求对象
    next();
  });
};

// 使用中间件
app.use(authMiddleware);

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/upload',express.static(path.join(__dirname, 'upload')));


app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/yzk', yzkRouter);
// 牛晓
app.use('/Niux', Niux);

// 王佑新
app.use('/xin', xinRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
